<template>
  <div class="login-container">
    <video
      class="video"
      src="../../assets/viedo/愤怒的小鸟愤怒的舔屏.mp4"
      muted="muted"
      autoplay="autoplay"
      loop="loop"
    ></video>

    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <!-- 电脑角标 -->
      <i
        :class="['jiaobiao', 'iconfont', jiaobiao]"
        @click="
          isErweiLogin = !isErweiLogin;
          isSmsLogin = false;
        "
      ></i>

      <!-- 常规登录 -->
      <div class="common-login" v-if="!isErweiLogin && !isSmsLogin">
        <h1>{{ title1 }}</h1>
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha" class="input1">
          <el-input
            maxlength="5"
            v-model.number="loginForm.captcha"
            class="captcha"
            @keydown.native.enter="submitForm('loginForm')"
          ></el-input>
          <span
            @click="updateCaptcha"
            class="captcha-svg"
            v-loading="loading"
            v-html="captchaSvg"
          ></span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>

        <!-- 手机登入图标及按钮 -->
        <el-form-item>
          <div class="sms">
            <img
              src="../../assets/img/xinxibar_shouji.png"
              alt=""
              class="phoneimg"
            />
            <a
              href="javascript:;"
              @click="isSmsLogin = true"
              style="color: #fff; font-size: 16px"
              >切换短信登录</a
            >
          </div>
        </el-form-item>
      </div>

      <!-- 切换二维码登录  -->
      <div class="erwei" v-else-if="isErweiLogin && !isSmsLogin">
        <h1>{{ title2 }}</h1>
        <div class="erwei-pic" v-loading="qrLoading">
          <img :src="imgBase64Url" alt="" />
          <i
            class="mask"
            :style="qrStyle"
            v-show="showQrMask"
            @click="getQrcode"
          ></i>
        </div>
        <p v-text="qrTip"></p>
      </div>

      <!-- 切换短信登录 -->
      <div class="smsContainer" v-else>
        <h1>{{ title3 }}</h1>
        <el-form-item label="手机号">
          <el-input maxlength="11" v-model="phoneNumber" class="captcha phone">
          </el-input>
          <span
            class="captcha-svg"
            style="color: #888; line-height: 45px; text-decoration: underline"
            @click="sendSmsCode"
            v-text="smsRetryMsg"
          ></span>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="smsCode"> </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="smsSubmit" @keydown.native.enter="smsSubmit">提交 </el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
//引入api中的方法
import * as api from "../../api/users";
import scancodeSuccessPic from "../../assets/img/34.png";
import invalidPic from "../../assets/img/yishixiao.png";

//引入socket.io
import socketIo from "socket.io-client";

import qr from "qrcode";
import { mapMutations } from "vuex";

var validateCaptcha = (rule, value, callback) => {
  //验证码
  if (value === "") {
    callback(new Error("请输入验证码"));
  } else {
    callback();
  }
};
var validateUsername = (rule, value, callback) => {
  var reg = /^[0-9A-Za-z_]{3,20}$/;
  if (!reg.test(value)) {
    callback("由数字、字母、下划线组成的3-20位");
  } else {
    callback();
  }
};
var validatePassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    callback();
  }
};
export default {
  name: "login",
  data() {
    return {
      smsDisabled: false, //控制是否能再次发送
      smsCode: "", //短信验证码
      phoneNumber: "", //手机号
      title1: "千峰管理系统",
      title2: "微信登录",
      title3: "短信验证登录",
      codeLoading: false, //验证码加载动画
      loading: true,
      isSmsLogin: false, //短信登录
      isErweiLogin: false, //是否为二维码登录
      captchaSvg: "", //验证码
      qrTip: "请使用手机微信扫码登录",
      imgBase64Url: "",
      showQrMask: false, //是否显示二维码遮罩
      qrLoading: true, //加载二维码的loading动画
      smsRetryMsg: "点击发送验证码", //xx秒后重新发送
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
      qrStyle: {
        //二维码遮罩
        backgroundImage: `url(${invalidPic})`,
        // backgroundImage:`url(${scancodeSuccessPic})`
      },
    };
  },
  created() {
    this.updateCaptcha();
  },
  computed: {
    jiaobiao() {
      return this.isErweiLogin
        ? "icon-diannaojiaobiao"
        : "icon-erweimajiaobiao";
    },
  },

  methods: {
    ...mapMutations(['SET_USER_INFO']),
    async smsSubmit() {
      let smsLoginRes = await api.smsLogin(this.smsCode);
      // console.log(smsLoginRes);
      let {
        userInfo,
        state,
        permission: { buttons },
        token,
      } = smsLoginRes.data;
      if (state) {
        localStorage.setItem("w-userInfo", JSON.stringify(userInfo));
        localStorage.setItem("w-permissionBtn", JSON.stringify(buttons));
        localStorage.setItem("w-token", token);
        this.$router.push("/")
      }
    },
    async sendSmsCode() {
      // console.log(this.phoneNumber);
      if (this.smsDisabled) {
        this.$message.error("1分钟只能发送一次");
        return;
      }

      let smsResult = await api.getSmsCode(this.phoneNumber);
      let { state } = smsResult.data;
      // console.log(state);
      if (state) {
        this.smsDisabled = true;

        this.$message.success("短信发送成功");
        this.smsSecond = 60;
        //短信发送进入倒计时
        this.smsInterval = setInterval(() => {
          this.smsSecond--;
          if (this.smsSecond === 0) {
            clearInterval(this.smsInterval);
            this.smsRetryMsg = "点击发送验证码";

            this.smsDisabled = false;
            return;
          }
          this.smsRetryMsg = `${this.smsSecond}秒重新发送`;
        }, 1000);
      }
      // console.log(smsResult);
    },

    async getQrcode(sid) {
      this.qrTip = "请使用手机微信扫码登录";
      this.showQrMask = false;
      this.qrLoading = true;
      sid = localStorage.getItem("w-sid") ?? sid;
      // console.log(sid)
      //调用接口获取二维码url
      let qrResult = await api.getQrcode(sid);
      // console.log(qrResult);

      let { scanCodeUrl, state: getQrState } = qrResult.data;
      // console.log(scanCodeUrl)
      if (getQrState) {
        qr.toDataURL(scanCodeUrl, (err, imgBase64Url) => {
          if (err) {
            this.$messageBox.error(err);
            return;
          }
          // console.log(imgBase64Url);
          this.imgBase64Url = imgBase64Url;

          this.qrLoading = false;
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    updateCaptcha() {
      this.loading = true;
      api.getCaptcha().then((res) => {
        // console.log(res);
        let { img } = res.data;
        this.captchaSvg = img;
        this.loading = false;
      });
    },
    async submitForm(formName) {
      //formName是表单的ref名字
      this.$refs[formName].validate((valid) => {
        // console.log(valid);
        if (valid) {
          //打开加载动画
          const loading = this.$loading({
            lock: true,
            text: "正在登录",
            spinner: "el-icon-loading",
            background: "rgba(0,0,0,0.7)",
          });

          //本地表单校验通过
          let { username, password, captcha } = this.loginForm;
          //校验验证码
          api.verifyCaptcha(captcha).then(async (res) => {
            // console.log(res);
            let { state } = res.data;
            if (state) {
              //验证码正确
              let loginRes = await api.login(username, password);
              // console.log(loginRes)
              let { state: loginState, msg, token, userInfo } = loginRes.data;
              if (loginState) {
                //关闭登录加载动画

                loading.close();

                //将token存到localStorage

                localStorage.setItem("w-token", token);

                localStorage.setItem("w-userInfo",JSON.stringify(userInfo))
                // console.log(userInfo)

                this.SET_USER_INFO(userInfo)
                this.$store.dispatch('FETCH_MENULIST')
                //登入成功跳转页面
                this.$router.push("/");
                //提示登录成功
                this.$message({
                  message: msg,
                  type: "success",
                  duration: 1500,
                });
              } else {
                //登录失败关闭加载动画
                loading.close();
                this.updateCaptcha()
              }
            } else {
              //登录失败关闭加载动画
              loading.close();
              this.updateCaptcha()
            }
          });
        } else {
          //表单校验不通过
        }
      });
    },
  },
  watch: {
    //监听切换短信登录逻辑
    isSmsLogin(val) {
      if (!val) {
        if (this.smsInterval) {
          clearInterval(this.smsInterval);
        }
        this.smsRetryMsg = "点击发送验证码";
      }
    },

    //监听二维码登录字段
    isErweiLogin(isErwei) {
      if (isErwei) {
        this.qrLoading = true;
        this.showQrMask = false;
        let io = socketIo("wss://chst.vip");

        //扫码成功
        io.on("scancodeSuccess", async (data) => {
          //显示二维码遮罩

          // console.log(data);
          // backgroundImage:`url(${scancodeSuccessPic})`
          this.showQrMask = true;
          this.qrStyle.backgroundImage = `url(${scancodeSuccessPic})`;
          let { state: scanCodeState, wechatCode } = data;
          if (scanCodeState) {
            //扫码成功
            let scanCodeRes = await api.wechatLogin(wechatCode);
            // console.log(scanCodeRes);

            let {
              state,
              userInfo,
              permission: { buttons },
              token,
            } = scanCodeRes.data;
            if (state) {
              localStorage.setItem("w-userInfo", JSON.stringify(userInfo));
              localStorage.setItem("w-permissionBtn", JSON.stringify(buttons));
              localStorage.setItem("w-token", token);

              //跳转至欢迎页
              this.$router.push("/");

              //关闭二维码遮罩
              this.showQrMask = false;
            }
          }
        });

        //二维码失效
        io.on("invalidCode", (data) => {
          // console.log(data);
          let { state } = data;
          if (!state) {
            this.showQrMask = true;
            this.qrTip = "二维码失效，请点击重亲获取二维码";
          }
        });

        //连接成功
        io.on("connectSuccess", async (data) => {
          // console.log(data);
          let { sid } = data;
          //唯一标识存至本地
          localStorage.setItem("w-sid", sid);

          this.getQrcode(sid);
        });
      }
    },
  },
};
</script>

<style scoped>
/* 
1.确认类名是否正确
2.确认权重够不够
3.是否要深度选择
*/

* {
  margin: 0;
  padding: 0;
}
.video {
  position: fixed;
  left: -300px;
  top: -200px;
}

.jiaobiao {
  color: #fff;
  font-size: 50px;
  right: -1px;
  top: -1px;
  cursor: pointer;
  position: absolute;
}
.login-loginForm {
  width: 400px;
  /* height: 433px;  */
  background: rgb(0, 0, 0, 0.3);
  position: fixed;
  right: 10%;
  top: 20%;
}
h1 {
  color: #fff;
  text-align: center;
  margin: 80px 0 60px 0;
}
p {
  font-size: 16px;
  color: #fff;
  margin: 50px 0 50px 0;
}
.login-container /deep/ .el-form-item__label {
  color: #fff;
}
.el-form {
  padding-bottom: 70px;
}
.el-form-item {
  margin-bottom: 22px;
}
.el-button {
  width: 250px;
  height: 40px;
  background: linear-gradient(90deg, #1596fb, #002dff);
}
.erwei {
  text-align: center;
}
.erwei-pic {
  margin: 0 100px;
  width: 200px;
  height: 200px;
}
.erwei img {
  width: 200px;
}

.login-container /deep/ .el-input__inner {
  width: 250px;
}
.input1 {
  position: relative;
}
.captcha-svg {
  cursor: pointer;
  position: absolute;
  right: 55px;
  border-radius: 2px;
  height: 40px;
}

/* 手机切换图标 */
.sms {
  position: relative;
  width: 250px;
  text-align: center;
}
.phoneimg {
  width: 30px;
  position: absolute;
  left: 45px;
  top: 5px;
}

/* 遮罩 */
.erwei-pic {
  position: relative;
}

.mask {
  width: 200px;
  height: 200px;
  position: absolute;
  left: 0;
  background-color: rgb(255, 255, 255, 0.8);
}
</style>